package com.eduhzy.ttw.teacher.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.MineInfo;
import com.eduhzy.ttw.commonsdk.utils.Utils;
import com.eduhzy.ttw.teacher.R;
import com.eduhzy.ttw.teacher.di.component.DaggerMineComponent;
import com.eduhzy.ttw.teacher.mvp.contract.MineContract;
import com.eduhzy.ttw.teacher.mvp.presenter.MinePresenter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.zhy.autolayout.AutoLinearLayout;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eduhzy.ttw.commonsdk.core.Constants.QRCODE.Person;
import static com.jess.arms.utils.Preconditions.checkNotNull;

;


/**
 * 我的
 *
 * @author xubo
 */
@Route(path = RouterHub.APP_MINEFRAGMENT)
public class MineFragment extends BaseFragment<MinePresenter> implements MineContract.View {

    @BindView(R.id.mine_avatar)
    QMUIRadiusImageView mineAvatar;
    @BindView(R.id.mine_name)
    TextView mineName;
    @BindView(R.id.mine_sid)
    TextView mineSid;
    @BindView(R.id.mine_qr_code)
    ImageView mineQrCode;
    @BindView(R.id.my_school_name)
    TextView mySchoolName;
    @BindView(R.id.mine_school)
    AutoLinearLayout mineSchool;
    @BindView(R.id.my_class_name)
    TextView myClassName;
    @BindView(R.id.mine_class)
    AutoLinearLayout mineClass;
    @BindView(R.id.mine_setting)
    AutoLinearLayout mineSetting;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeLayout;
    private MineInfo mData;
    private QMUITipDialog uploadLoading;

    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerMineComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_mine, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter.getUserInfo(SPUtils.getInstance().getString(Constants.USERID));
        mSwipeLayout.setOnRefreshListener(() -> {
            mPresenter.getUserInfo(SPUtils.getInstance().getString(Constants.USERID));
        });
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        if (mSwipeLayout != null)
            mSwipeLayout.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        if (mSwipeLayout != null)
            mSwipeLayout.setRefreshing(false);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    //, R.id.mine_avatar
    @OnClick({R.id.mine_person, R.id.mine_qr_code, R.id.mine_school, R.id.mine_class, R.id.mine_order, R.id.mine_setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mine_person:
                ARouter.getInstance().build(RouterHub.APP_PERSONINFOACTIVITY)
                        .withParcelable(Constants.ROUTER_DATA, mData)
                        .withString(Intent.EXTRA_TITLE, Constants.PERSON_INFO)
                        .navigation();
                break;
            case R.id.mine_avatar:
                break;
            case R.id.mine_qr_code:
                ARouter.getInstance().build(RouterHub.APP_GENERATECODEACTIVITY)
                        .withString(Intent.EXTRA_TITLE, Constants.QR_CODE_CARD)
                        .withString(Constants.GENERATE_CODE, RxUtil.getUserCode(mData.getBaseNo()))
                        .withInt(Constants.QR_CODE_TYPE, Person)
                        .navigation();
                break;
            case R.id.mine_school:
                Utils.navigationWithTitle(RouterHub.APP_MINESCHOOLACTIVITY, Constants.CHOOSE_PROVINCE);
                break;
            case R.id.mine_class:
                Utils.navigationWithTitle(RouterHub.APP_MINECLASSACTIVITY, Constants.MINECLASS);
                break;
            case R.id.mine_order:
                Utils.navigationWithTitle(RouterHub.COURSELIVE_MINEORDERACTIVITY, Constants.MINEORDER);
                break;
            case R.id.mine_setting:
                Utils.navigationWithTitle(RouterHub.APP_SETUPACTIVITY, Constants.SETTING);
                break;
            default:
        }
    }

    @Subscriber(tag = RouterHub.APP_MINEFRAGMENT)
    public void onEvents(Message msg) {
        switch (msg.what) {
            case EventBusTags.UPDATE_AVATAR:
                String avatar = (String) msg.obj;
                mData.setTempAvatar(avatar);
                updateAvatar(avatar);
                break;
            case EventBusTags.PERSON_UPDATE_SUCCESS:
                String name = (String) msg.obj;
                if (ObjectUtils.isNotEmpty(name)) {
                    mineName.setText(name);
                    mData.setRealName(name);
                } else {
                    mData.setGender(msg.arg1);
                }
                break;
            case EventBusTags.PHONE_UPDATE_SUCCESS:
                String phone = (String) msg.obj;
                if (ObjectUtils.isNotEmpty(phone)) {
                    mData.setMobile(phone);
                }
                break;
            case EventBusTags.CHOOSE_SCHOOL_SUCCESS:
                mPresenter.getUserInfo(SPUtils.getInstance().getString(Constants.USERID));
                break;
            default:
        }
    }

    @Override
    public void update(MineInfo data) {
        this.mData = data;
        mineName.setText(data.getRealName());
        mineSid.setText(data.getBaseNo() + "");
        mySchoolName.setText(data.getGroupName());
        updateAvatar(data.getTempAvatar());
        if (SPUtils.getInstance().getBoolean(Constants.TIP_SCHOOL_OR_CLASS, true)) {
            if (!data.isHasSchool() || !data.isHasClazz()) {
                showSchoolClassTipDialog(data.isHasSchool(), data.isHasClazz());
            }
        }

    }

    public void showSchoolClassTipDialog(boolean hasSchool, boolean hasClazz) {
        QMUIDialog tipDailog = getQmuiDialog(R.layout.dialog_tip_no_school_or_class);
        TextView title = (TextView) tipDailog.findViewById(R.id.tv_title);
        if (!hasSchool) {
            title.setText(R.string.tip_no_school);
        } else if (!hasClazz) {
            title.setText(R.string.tip_no_class);
        }
        tipDailog.findViewById(R.id.btn_cancel).setOnClickListener((view) -> {
            SPUtils.getInstance().put(Constants.TIP_SCHOOL_OR_CLASS, false, SPUtils.getInstance().contains(Constants.TIP_SCHOOL_OR_CLASS));
            Message msg = Message.obtain();
            msg.what = EventBusTags.UPDATE_TIP_SCHOOL_AND_CLASS;
            EventBus.getDefault().post(msg, RouterHub.APP_SETUPACTIVITY);
            tipDailog.dismiss();
        });

        Button btnOk = tipDailog.findViewById(R.id.btn_ok);
        btnOk.setOnClickListener((view) -> {
            if (!hasSchool) {
                Utils.navigationWithTitle(RouterHub.APP_MINESCHOOLACTIVITY, Constants.CHOOSE_PROVINCE);
            } else if (!hasClazz) {
                Utils.navigationWithTitle(RouterHub.APP_MINECLASSACTIVITY, Constants.MINECLASS);
            }
            tipDailog.dismiss();
        });
    }

    @NonNull
    private QMUIDialog getQmuiDialog(int resId) {
        QMUIDialog transfer = new QMUIDialog(getActivity(), R.style.TransparentDialogTheme);
        transfer.setContentView(resId);
        transfer.show();
        transfer.setCancelable(false);
        Window window = transfer.getWindow();
        //设置窗口位置
        window.setGravity(Gravity.CENTER);
        //获取窗口属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //获取窗口管理者
        WindowManager windowManager = getActivity().getWindowManager();
        //获取真机参数
        Display display = windowManager.getDefaultDisplay();
        //设置窗口大小
        //根据autolayout来适配当前大小
        lp.width = (int) (display.getWidth() * 977 / 1080f);
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        //给窗口设置属性
        window.setAttributes(lp);
        return transfer;
    }

    public void updateAvatar(String data) {
        mineAvatar.post(() ->
                Glide.with(this)
                        .load(data)
                        .apply(RequestOptions.placeholderOf(R.drawable.img_touxiang).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL))
                        .into(mineAvatar));
    }


}
